<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mgroup extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
	
    public function getListGroup($number = 0,$offset = 0){
        $limit = $offset ? intval($offset) : '0';
        
        $sql = "SELECT g.id, g.name FROM tbl_group AS g ORDER BY g.id DESC";
        
        $count = $this->db->query($sql)->num_rows();
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        
        $xs = $this->db->query($sql.$xdata)->result_object();
        return array('data' => $xs, 'count' => $count);
    }
    
    public function getGroupDetail($id){
        $sql = "SELECT * FROM tbl_group WHERE id = ".$id;
        $data = $this->db->query($sql)->row_object();
        
        return $data;
    }
    
    public function addGroup($name,$note){
        $data = array(
            'name' => $name,
            'name_ascii' => $this->get_ascii($name),
            'note' => $note
        );
        
        $count = $this->db->query("SELECT id FROM tbl_group WHERE name_ascii = '".$data['name_ascii']."'")->num_rows();
        if($count === 0){
            $this->db->insert('tbl_group', $data);
            return 200;
        }
        return 201;
    }
    
    public function editGroup($id,$name,$note){
        $data = array(
            'name' => $name,
            'name_ascii' => $this->get_ascii($name),
            'note' => $note
        );
        
        $count = $this->db->query("SELECT id FROM tbl_group WHERE name_ascii = '".$data['name_ascii']."' AND id != ".$id)->num_rows();
        if($count === 0){
            $this->db->update('tbl_group', $data, "id = ".$id);
            return 200;
        }
        return 201;
    } 
    
    public function deleteGroup($id){
        $this->db->delete('tbl_group', "id = ".$id);
        return 200;
    }
}
